/**
 * 微信小程序第三方平台上传路由
 */
const express = require('express');
const path = require('path');
const fs = require('fs-extra');
const axios = require('axios');
const miniprogramUploadManager = require('../utils/miniprogramUploadManager');
const logManager = require('../utils/logManager');
const templateDeleteQueue = require('../utils/templateDeleteQueue');

const router = express.Router();

/**
 * 检测小程序构建产物路径
 */
async function detectMiniprogramPath(projectPath, projectId) {
  const possiblePaths = [
    path.join(projectPath, 'docker-build-output'),  // Docker构建输出目录
    path.join(projectPath, 'docker-build-output', 'build', 'mp-weixin'),
    path.join(projectPath, 'dist', 'build', 'mp-weixin'),
    path.join(projectPath, 'unpackage', 'dist', 'build', 'mp-weixin'),
    path.join(projectPath, 'dist', 'build', 'mp-alipay'),
    path.join(projectPath, 'unpackage', 'dist', 'build', 'mp-alipay'),
    path.join(projectPath, 'dist', 'mp-weixin'),
    path.join(projectPath, 'dist', 'mp-alipay'),
    projectPath
  ];

  for (const testPath of possiblePaths) {
    const projectConfigPath = path.join(testPath, 'project.config.json');
    if (await fs.pathExists(projectConfigPath)) {
      const relativePath = testPath.replace(projectPath, '').substring(1) || '根目录';
      logManager.sendLog(projectId, {
        level: 'info',
        message: `✅ 找到小程序配置文件: ${relativePath}/project.config.json`
      });
      return testPath;
    }
  }

  return null;
}

/**
 * 调试接口 - 查看项目目录结构
 * GET /api/miniprogram/debug/:projectId
 */
router.get('/debug/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    const projectPath = path.join(__dirname, '../../temp', projectId);

    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    // 递归读取目录结构
    async function readDirRecursive(dirPath, depth = 0, maxDepth = 3) {
      if (depth > maxDepth) return [];

      const items = await fs.readdir(dirPath);
      const result = [];

      for (const item of items) {
        const fullPath = path.join(dirPath, item);
        const stats = await fs.stat(fullPath);
        const relativePath = fullPath.replace(projectPath, '').substring(1);

        if (stats.isDirectory()) {
          const children = await readDirRecursive(fullPath, depth + 1, maxDepth);
          result.push({
            name: item,
            type: 'directory',
            path: relativePath,
            children
          });
        } else {
          result.push({
            name: item,
            type: 'file',
            path: relativePath,
            size: stats.size
          });
        }
      }

      return result;
    }

    const structure = await readDirRecursive(projectPath);

    // 检测可能的小程序路径
    const uploadPath = await detectMiniprogramPath(projectPath, projectId);

    res.json({
      success: true,
      projectId,
      projectPath,
      uploadPath,
      structure
    });

  } catch (error) {
    console.error('读取项目结构失败:', error);
    res.status(500).json({
      error: '读取项目结构失败',
      message: error.message
    });
  }
});

/**
 * 上传小程序代码
 * POST /api/miniprogram/upload
 */
router.post('/upload', async (req, res) => {
  try {
    const {
      projectId,
      authAppid,
      version,
      desc,
      accessToken,
      extConfig,
      robot,
      setting
    } = req.body;

    if (!projectId) {
      return res.status(400).json({ error: '项目ID不能为空' });
    }

    if (!authAppid) {
      return res.status(400).json({ error: '授权小程序appid不能为空' });
    }

    const projectPath = path.join(__dirname, '../../temp', projectId);

    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在,请先构建项目' });
    }

    // 检测小程序构建产物路径
    const uploadPath = await detectMiniprogramPath(projectPath, projectId);

    if (!uploadPath) {
      const errorMsg = '未找到小程序构建产物,请确认: 1) 已构建小程序项目 2) 构建平台选择了小程序 3) 构建成功完成';

      logManager.sendLog(projectId, {
        level: 'error',
        message: `❌ ${errorMsg}`
      });

      return res.status(404).json({
        error: '未找到小程序构建产物',
        message: errorMsg,
        tip: '可以访问 /api/miniprogram/debug/' + projectId + ' 查看项目目录结构'
      });
    }

    // 执行上传
    const uploadOptions = {
      version: version || miniprogramUploadManager.generateVersion(),
      desc: desc || `自动化构建上传 - ${new Date().toLocaleString('zh-CN')}`,
      accessToken,
      extConfig,
      robot,
      setting
    };

    const result = await miniprogramUploadManager.upload(
      uploadPath,
      authAppid,
      uploadOptions
    );

    if (result.success) {
      logManager.sendLog(projectId, {
        level: 'info',
        message: `✅ 小程序上传成功`,
        data: result
      });

      res.json({
        success: true,
        message: '小程序代码上传成功',
        data: result
      });
    } else {
      logManager.sendLog(projectId, {
        level: 'error',
        message: `❌ 小程序上传失败`,
        data: result
      });

      res.status(500).json({
        success: false,
        error: '小程序上传失败',
        message: result.error
      });
    }

  } catch (error) {
    console.error('上传小程序失败:', error);
    res.status(500).json({
      error: '上传小程序失败',
      message: error.message
    });
  }
});

/**
 * 生成预览二维码
 * POST /api/miniprogram/preview
 */
router.post('/preview', async (req, res) => {
  try {
    const {
      projectId,
      authAppid,
      accessToken,
      pagePath,
      searchQuery,
      extConfig
    } = req.body;

    if (!projectId) {
      return res.status(400).json({ error: '项目ID不能为空' });
    }

    if (!authAppid) {
      return res.status(400).json({ error: '授权小程序appid不能为空' });
    }

    const projectPath = path.join(__dirname, '../../temp', projectId);

    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    const uploadPath = await detectMiniprogramPath(projectPath, projectId);

    if (!uploadPath) {
      return res.status(404).json({
        error: '未找到小程序构建产物',
        message: '请先构建小程序项目'
      });
    }

    const qrcodePath = path.join(__dirname, '../../downloads', `preview_${projectId}_${Date.now()}.jpg`);

    const previewOptions = {
      accessToken,
      pagePath,
      searchQuery,
      extConfig,
      qrcodeOutputDest: qrcodePath,
      qrcodeFormat: 'image'
    };

    const result = await miniprogramUploadManager.preview(
      uploadPath,
      authAppid,
      previewOptions
    );

    if (result.success) {
      const qrcodeUrl = `/downloads/${path.basename(qrcodePath)}`;

      res.json({
        success: true,
        message: '预览二维码生成成功',
        data: {
          ...result,
          qrcodeUrl
        }
      });
    } else {
      res.status(500).json({
        success: false,
        error: '生成预览二维码失败',
        message: result.error
      });
    }

  } catch (error) {
    console.error('生成预览二维码失败:', error);
    res.status(500).json({
      error: '生成预览二维码失败',
      message: error.message
    });
  }
});

/**
 * 批量上传多个授权小程序
 * POST /api/miniprogram/batch-upload
 */
router.post('/batch-upload', async (req, res) => {
  try {
    const {
      projectId,
      authAppids,
      version,
      desc,
      accessToken,
      extConfig
    } = req.body;

    if (!projectId) {
      return res.status(400).json({ error: '项目ID不能为空' });
    }

    if (!authAppids || !Array.isArray(authAppids) || authAppids.length === 0) {
      return res.status(400).json({ error: '授权小程序appid列表不能为空' });
    }

    const projectPath = path.join(__dirname, '../../temp', projectId);

    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    const uploadPath = await detectMiniprogramPath(projectPath, projectId);

    if (!uploadPath) {
      return res.status(404).json({
        error: '未找到小程序构建产物',
        message: '请先构建小程序项目'
      });
    }

    const uploadOptions = {
      version: version || miniprogramUploadManager.generateVersion(),
      desc: desc || `批量自动化构建上传 - ${new Date().toLocaleString('zh-CN')}`,
      accessToken,
      extConfig
    };

    logManager.sendLog(projectId, {
      level: 'info',
      message: `📱 开始批量上传 ${authAppids.length} 个小程序`,
      data: { authAppids }
    });

    const results = await miniprogramUploadManager.batchUpload(
      uploadPath,
      authAppids,
      uploadOptions
    );

    const successCount = results.filter(r => r.success).length;
    const failCount = results.length - successCount;

    logManager.sendLog(projectId, {
      level: 'info',
      message: `✅ 批量上传完成: 成功 ${successCount} 个, 失败 ${failCount} 个`,
      data: { results }
    });

    res.json({
      success: true,
      message: `批量上传完成: 成功 ${successCount} 个, 失败 ${failCount} 个`,
      data: {
        total: results.length,
        successCount,
        failCount,
        results
      }
    });

  } catch (error) {
    console.error('批量上传失败:', error);
    res.status(500).json({
      error: '批量上传失败',
      message: error.message
    });
  }
});

/**
 * 获取上传历史
 * GET /api/miniprogram/history/:projectId/:authAppid
 */
router.get('/history/:projectId/:authAppid', async (req, res) => {
  try {
    const { projectId, authAppid } = req.params;
    const { accessToken } = req.query;

    const projectPath = path.join(__dirname, '../../temp', projectId);

    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    const uploadPath = await detectMiniprogramPath(projectPath, projectId);

    if (!uploadPath) {
      return res.status(404).json({
        error: '未找到小程序构建产物',
        message: '请先构建小程序项目'
      });
    }

    const result = await miniprogramUploadManager.getUploadHistory(
      uploadPath,
      authAppid,
      { accessToken }
    );

    if (result.success) {
      res.json({
        success: true,
        data: result.history
      });
    } else {
      res.status(500).json({
        success: false,
        error: '获取上传历史失败',
        message: result.error
      });
    }

  } catch (error) {
    console.error('获取上传历史失败:', error);
    res.status(500).json({
      error: '获取上传历史失败',
      message: error.message
    });
  }
});

/**
 * 生成版本号
 * GET /api/miniprogram/generate-version
 */
router.get('/generate-version', (req, res) => {
  try {
    const version = miniprogramUploadManager.generateVersion();
    res.json({
      success: true,
      version
    });
  } catch (error) {
    res.status(500).json({
      error: '生成版本号失败',
      message: error.message
    });
  }
});

/**
 * 生成版本描述
 * GET /api/miniprogram/generate-desc/:projectId
 */
router.get('/generate-desc/:projectId', async (req, res) => {
  try {
    const { projectId } = req.params;
    const projectPath = path.join(__dirname, '../../temp', projectId);

    if (!await fs.pathExists(projectPath)) {
      return res.status(404).json({ error: '项目不存在' });
    }

    // 检测小程序构建产物路径
    const uploadPath = await detectMiniprogramPath(projectPath, projectId);
    if (!uploadPath) {
      return res.status(404).json({ error: '未找到小程序构建产物' });
    }

    // 读取构建配置文件获取域名信息
    const buildConfigPath = path.join(projectPath, '.build-config.json');
    let domain = '';

    if (await fs.pathExists(buildConfigPath)) {
      try {
        const buildConfig = await fs.readJson(buildConfigPath);
        domain = buildConfig.apiUrl || '';
        // 如果有完整URL，提取域名
        if (domain && domain.startsWith('http')) {
          const url = new URL(domain);
          domain = url.hostname;
        }
      } catch (err) {
        console.error('读取.build-config.json失败:', err);
      }
    }

    // 读取 config.json
    const configPath = path.join(uploadPath, 'static', 'config.json');
    let configVersion = '';

    if (await fs.pathExists(configPath)) {
      try {
        const config = await fs.readJson(configPath);
        configVersion = config.version || '';
      } catch (err) {
        console.error('读取config.json失败:', err);
      }
    }

    // 生成时间戳
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hour = String(now.getHours()).padStart(2, '0');
    const minute = String(now.getMinutes()).padStart(2, '0');
    const second = String(now.getSeconds()).padStart(2, '0');
    const timestamp = `${year}-${month}-${day} ${hour}:${minute}:${second}`;

    // 组装描述
    let desc = '';
    if (domain) {
      desc += `域名: ${domain}\n`;
    }
    if (configVersion) {
      desc += `版本: ${configVersion}\n`;
    }
    desc += `构建时间: ${timestamp}`;

    res.json({
      success: true,
      desc,
      domain,
      configVersion,
      timestamp
    });
  } catch (error) {
    console.error('生成版本描述失败:', error);
    res.status(500).json({
      error: '生成版本描述失败',
      message: error.message
    });
  }
});

// ==================== 草稿箱管理相关接口 ====================

/**
 * 获取第三方平台 component_access_token
 * POST /api/miniprogram/component-token
 */
router.post('/component-token', async (req, res) => {
  try {
    const { component_appid, component_appsecret, component_verify_ticket } = req.body;

    if (!component_appid || !component_appsecret || !component_verify_ticket) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const response = await axios.post(
      'https://api.weixin.qq.com/cgi-bin/component/api_component_token',
      {
        component_appid,
        component_appsecret,
        component_verify_ticket
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('获取 component_access_token 失败:', error);
    res.status(500).json({
      success: false,
      error: '获取 component_access_token 失败',
      message: error.message
    });
  }
});

/**
 * 获取草稿箱列表
 * GET /api/miniprogram/draft-list
 */
router.get('/draft-list', async (req, res) => {
  try {
    const { access_token } = req.query;

    if (!access_token) {
      return res.status(400).json({
        success: false,
        error: '缺少 access_token 参数'
      });
    }

    const response = await axios.get(
      'https://api.weixin.qq.com/wxa/gettemplatedraftlist',
      {
        params: {
          access_token
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('获取草稿箱列表失败:', error);
    res.status(500).json({
      success: false,
      error: '获取草稿箱列表失败',
      message: error.message
    });
  }
});

/**
 * 添加草稿到模版库
 * POST /api/miniprogram/add-to-template
 */
router.post('/add-to-template', async (req, res) => {
  try {
    const { access_token, draft_id, template_type } = req.body;

    if (!access_token || !draft_id) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const response = await axios.post(
      `https://api.weixin.qq.com/wxa/addtotemplate?access_token=${access_token}`,
      {
        draft_id,
        template_type: template_type || 0
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('添加到模版库失败:', error);
    res.status(500).json({
      success: false,
      error: '添加到模版库失败',
      message: error.message
    });
  }
});

/**
 * 获取模版库列表
 * GET /api/miniprogram/template-list
 */
router.get('/template-list', async (req, res) => {
  try {
    const { access_token, template_type } = req.query;

    if (!access_token) {
      return res.status(400).json({
        success: false,
        error: '缺少 access_token 参数'
      });
    }

    const response = await axios.get(
      'https://api.weixin.qq.com/wxa/gettemplatelist',
      {
        params: {
          access_token,
          template_type: template_type || 0
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('获取模版库列表失败:', error);
    res.status(500).json({
      success: false,
      error: '获取模版库列表失败',
      message: error.message
    });
  }
});

/**
 * 上传小程序代码到草稿箱
 * POST /api/miniprogram/commit-code
 */
router.post('/commit-code', async (req, res) => {
  try {
    const { access_token, template_id, ext_json, user_version, user_desc } = req.body;

    if (!access_token || !template_id || !user_version || !user_desc) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const response = await axios.post(
      `https://api.weixin.qq.com/wxa/commit?access_token=${access_token}`,
      {
        template_id,
        ext_json: ext_json || '{}',
        user_version,
        user_desc
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('上传代码失败:', error);
    res.status(500).json({
      success: false,
      error: '上传代码失败',
      message: error.message
    });
  }
});

/**
 * 删除模版(单个,直接删除)
 * POST /api/miniprogram/delete-template
 */
router.post('/delete-template', async (req, res) => {
  try {
    const { access_token, template_id } = req.body;

    if (!access_token || !template_id) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const response = await axios.post(
      `https://api.weixin.qq.com/wxa/deletetemplate?access_token=${access_token}`,
      {
        template_id
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('删除模版失败:', error);
    res.status(500).json({
      success: false,
      error: '删除模版失败',
      message: error.message
    });
  }
});

/**
 * 批量删除模版(创建删除任务)
 * POST /api/miniprogram/batch-delete-templates
 */
router.post('/batch-delete-templates', async (req, res) => {
  try {
    const { access_token, templates } = req.body;

    if (!access_token || !templates || !Array.isArray(templates) || templates.length === 0) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数或模版列表为空'
      });
    }

    // 创建删除任务
    const taskId = templateDeleteQueue.createTask(access_token, templates);

    res.json({
      success: true,
      taskId,
      message: `已创建删除任务,共 ${templates.length} 个模版`
    });
  } catch (error) {
    console.error('创建批量删除任务失败:', error);
    res.status(500).json({
      success: false,
      error: '创建批量删除任务失败',
      message: error.message
    });
  }
});

/**
 * 获取删除任务状态
 * GET /api/miniprogram/delete-task/:taskId
 */
router.get('/delete-task/:taskId', async (req, res) => {
  try {
    const { taskId } = req.params;

    const task = templateDeleteQueue.getTask(taskId);

    if (!task) {
      return res.status(404).json({
        success: false,
        error: '任务不存在'
      });
    }

    res.json({
      success: true,
      task
    });
  } catch (error) {
    console.error('获取删除任务状态失败:', error);
    res.status(500).json({
      success: false,
      error: '获取删除任务状态失败',
      message: error.message
    });
  }
});

/**
 * 设置第三方服务平台服务器域名
 * POST /api/miniprogram/modify-server-domain
 */
router.post('/modify-server-domain', async (req, res) => {
  try {
    const { access_token, action, wxa_server_domain, is_modify_published_together } = req.body;

    if (!access_token || !action) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const requestBody = { action };
    if (wxa_server_domain) requestBody.wxa_server_domain = wxa_server_domain;
    if (typeof is_modify_published_together !== 'undefined') {
      requestBody.is_modify_published_together = is_modify_published_together;
    }

    const response = await axios.post(
      `https://api.weixin.qq.com/cgi-bin/component/modify_wxa_server_domain?access_token=${access_token}`,
      requestBody,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('设置第三方服务平台域名失败:', error);
    res.status(500).json({
      success: false,
      error: '设置第三方服务平台域名失败',
      message: error.response?.data || error.message
    });
  }
});

/**
 * 设置小程序服务器域名
 * POST /api/miniprogram/modify-miniprogram-domain
 */
router.post('/modify-miniprogram-domain', async (req, res) => {
  try {
    const {
      access_token,
      action,
      requestdomain,
      wsrequestdomain,
      uploaddomain,
      downloaddomain,
      udpdomain,
      tcpdomain
    } = req.body;

    if (!access_token || !action) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const requestBody = { action };
    if (requestdomain) requestBody.requestdomain = requestdomain;
    if (wsrequestdomain) requestBody.wsrequestdomain = wsrequestdomain;
    if (uploaddomain) requestBody.uploaddomain = uploaddomain;
    if (downloaddomain) requestBody.downloaddomain = downloaddomain;
    if (udpdomain) requestBody.udpdomain = udpdomain;
    if (tcpdomain) requestBody.tcpdomain = tcpdomain;

    const response = await axios.post(
      `https://api.weixin.qq.com/wxa/modify_domain_directly?access_token=${access_token}`,
      requestBody,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('设置小程序域名失败:', error);
    res.status(500).json({
      success: false,
      error: '设置小程序域名失败',
      message: error.response?.data || error.message
    });
  }
});

/**
 * 设置订单页面path
 * POST /api/miniprogram/add-to-template-path
 */
router.post('/add-to-template-path', async (req, res) => {
  try {
    const { access_token, batch_req } = req.body;

    if (!access_token || !batch_req) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const response = await axios.post(
      `https://api.weixin.qq.com/wxa/addtotemplate?access_token=${access_token}`,
      { batch_req },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('设置订单页面path失败:', error);
    res.status(500).json({
      success: false,
      error: '设置订单页面path失败',
      message: error.response?.data || error.message
    });
  }
});

/**
 * 设置小程序隐私保护指引
 * POST /api/miniprogram/set-privacy-setting
 */
router.post('/set-privacy-setting', async (req, res) => {
  try {
    const { access_token, privacy_ver, setting_list, owner_setting } = req.body;

    if (!access_token || !setting_list) {
      return res.status(400).json({
        success: false,
        error: '缺少必要参数'
      });
    }

    const response = await axios.post(
      `https://api.weixin.qq.com/cgi-bin/component/setprivacysetting?access_token=${access_token}`,
      {
        privacy_ver: privacy_ver || 2,
        setting_list,
        owner_setting
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('设置隐私保护指引失败:', error);
    res.status(500).json({
      success: false,
      error: '设置隐私保护指引失败',
      message: error.response?.data || error.message
    });
  }
});

module.exports = router;
